package com.sen.common.orm.ibatis;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.orm.ibatis.SqlMapClientCallback;

import com.ibatis.sqlmap.client.SqlMapExecutor;
import com.sen.common.orm.PublicDao;

/**
 * ibatis的PublicDAO实现.
 * 
 * @author sen
 */
public class IbatisPublicDao extends BaseSqlMapDaoSupport implements PublicDao {

	public Object insert(String sqlMapId, Object obj) {
		return getSqlMapClientTemplate().insert(sqlMapId, obj);
	}
	
	@SuppressWarnings("unchecked")
	public Object batchExecute(final String sqlMapId, final List<Object> objs) {
		return getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
			public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
				
				executor.startBatch();
				int batch = 0;
				int retVal = 0;
				if (objs != null && !objs.isEmpty()) {
					for (Object o : objs) {
						executor.insert(sqlMapId, o);
						batch ++;
						if(batch == 500){ 
							retVal += executor.executeBatch();
					     	batch = 0;
						}
					}
				}
				if(batch != 0){
					retVal += executor.executeBatch(); 
				}
				return retVal;
			}
		});
	}

	public int update(String sqlMapId, Object obj) {
		return getSqlMapClientTemplate().update(sqlMapId, obj);
	}

	public int delete(String sqlMapId) {
		return delete(sqlMapId, null);
	}

	public int delete(String sqlMapId, Object obj) {
		return getSqlMapClientTemplate().delete(sqlMapId, obj);
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> query(String sqlMapId, Object param, int skip, int max) {
		if (max == 0) {
			return getSqlMapClientTemplate().queryForList(sqlMapId, param);
		}
		return getSqlMapClientTemplate().queryForList(sqlMapId, param, skip,
				max);
	}

	public <T> List<T> query(String sqlMapId) {
		return query(sqlMapId, null);
	}

	public <T> List<T> query(String sqlMapId, Object param) {
		return query(sqlMapId, param, 0, 0);
	}

	public <T> T querySingle(String sqlMapId) {
		List<T> list = query(sqlMapId);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	public <T> T querySingle(String sqlMapId, Object param) {
		List<T> list = query(sqlMapId, param);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

}
